import {reactive, ref, toRefs, getCurrentInstance, watch,shallowRef} from "vue"
/**
 * 富文本编辑器
*/
export default function () {
    const {proxy} = getCurrentInstance()

    const editorRef = shallowRef() // 编辑器实例，必须用 shallowRef
    const editorHtml = ref("") // 内容 HTML
    const editorToolbarConfig = {
        excludeKeys: [
            // 排除不需要的菜单
            "insertLink",
            "insertImage",
            "editImage",
            "viewImageLink",
            "insertVideo",
            // "uploadVideo",
            "editVideoSize",
            "emotion",
            // "group-video"
        ],
    }
    const editorConfig = { placeholder: "请输入内容...", MENU_CONF: {} }
    const handleEditorCreated = (editor) => {
        editorRef.value = editor // 记录 editor 实例，重要！
    }
    editorConfig.MENU_CONF["uploadImage"] = {
        // 自定义上传
        async customUpload(file, insertFn) {
            let data = new FormData();
            data.append("file", file);
            proxy.$axios.post("resources/public", data).then((res) => {
                if (res.data.code == 200) {
                    let img = res.data.data;
                    insertFn(proxy.imgUrl + img.url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填

                } else {
                    proxy.$message({
                        message:res.data.msg || '错误',
                        type: "error"
                    })
                }
            }).catch(err => {

            })
        }
    }
    editorConfig.MENU_CONF["uploadVideo"] = {
        // 自定义上传
        async customUpload(file, insertFn) {
            let data = new FormData();
            data.append("file", file);
            proxy.$axios.post("resources/public", data).then((res) => {
                if (res.data.code == 200) {
                    let img = res.data.data;
                    insertFn(proxy.imgUrl + img.url) // 最后插入图片 insertFn(url, alt, href)，alt：描述，href:链接，后面非必填

                } else {
                    proxy.$message({
                        message:res.data.msg || '错误',
                        type: "error"
                    })
                }
            }).catch(err => {

            })
        }
    }

    const htmlAddImgUrl = (html)=>{
        html = html.replace(/<img [^>]*src=['"]/g, `<img src="${proxy.imgUrl}`) // 往图片追加根域名和'/'
        html = html.replace(/<source [^>]*src=['"]/g, `<source src="${proxy.imgUrl}`)
        return html
    }
    const htmlRemoveImgUrl = (html)=>{
        let replaceChar = `${proxy.imgUrl}`;
        // html = html.replace(/\bhttps?:\/\/(.*?)\/+/gi, "") // 去除图片根域名以及根域名后面的'/'
        html = html.replace(new RegExp(replaceChar, "g"), "") // 去除图片根域名以及根域名后面的'/'
        return html
    }

    return {
        editorRef,editorHtml,editorConfig,editorToolbarConfig,handleEditorCreated,htmlAddImgUrl,htmlRemoveImgUrl
    }
}
